package com.linkin.homepage.base;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;

import androidx.fragment.app.FragmentActivity;

import com.bumptech.glide.Glide;
import com.linkin.homepage.R;
import com.linkin.homepage.base.loading.ILoadingAnimation;
import com.linkin.homepage.base.loading.LoadingView;
import com.linkin.homepage.base.util.NetStatusUtils;
import com.linkin.homepage.base.util.ScreenUtils;
import com.linkin.homepage.util.ToastUitl;

import java.lang.ref.WeakReference;

public abstract class BaseActivity extends FragmentActivity implements ILoadingAnimation {

    protected Context mContext;
    private ActivityHandler mActivityHandler;

    private String mTag = getClass().getSimpleName();
    private boolean mResumed = false;
    private boolean mActivityDestroyed = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        beforeLoading();

        mActivityDestroyed = false;
        mContext = this;
        mActivityHandler = new ActivityHandler(this);

        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        if (isFullScreen()) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }

        View view = getLayoutInflater().inflate(getLayoutResource(), null,false);

        View contentView = fitsStatusBar(view);
        setContentView(contentView);

        initLoadingView(view);
        initView();
        initData();
    }

    protected abstract int getLayoutResource();

    /**
     * 初始化一些操作，默认实现了
     */
    protected void beforeLoading() {

    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mResumed = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        mResumed = false;

        //https://blog.csdn.net/z1074971432/article/details/10517449
        if (isFinishing()) {
            doDestroy();
        }
    }

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        return super.onCreateView(name, context, attrs);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
        super.startActivityForResult(intent, requestCode, options);
        setActivityAnimation(true);
    }

    @Override
    public void finish() {
        if (isAlive()) {
            super.finish();
            setActivityAnimation(false);
        }
    }

    @Override
    protected void onDestroy() {
        doDestroy();
        super.onDestroy();
    }

    protected Context getContext() {
        return mContext;
    }

    private void doDestroy() {
        if (!mActivityDestroyed) {
            mActivityDestroyed = true;
            Glide.get(this).clearMemory();
            clear();
            getHandler().removeCallbacksAndMessages(null);
        }
    }

    public boolean isActivityDestroyed() {
        return mActivityDestroyed || isDestroyed() || isFinishing();
    }

    public boolean isActivityAlive() {
        return !isActivityDestroyed();
    }

    public boolean isAlive() {
        return isActivityAlive();
    }

    public boolean isResume() {
        return mResumed;
    }

    /**
     * 设置activity启动动画和退出动画
     */
    protected void setActivityAnimation(boolean startActivity) {
        if (startActivity) {
            overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_stay_orig);
        } else {
            overridePendingTransition(R.anim.base_stay_orig, R.anim.push_right_out);
        }
    }

    protected abstract void initView();

    protected void initData() {
    }

    private void refreshDataWithCheckNetWork() {
        if (NetStatusUtils.isConnected(this)) {
            refreshData();
        } else {
            ToastUitl.showShort("网络未连接，请连接网络后重试！");
        }
    }

    protected void refreshData() {
    }

    protected String getTag() {
        return mTag;
    }

    protected abstract void clear();

    protected boolean needSwipeBack() {
        return false;
    }

    protected boolean needHideSoftInput() {
        return true;
    }

    /**
     * 窗口是否全屏
     */
    protected boolean isFullScreen() {
        return false;
    }

    protected boolean needSetStatusBarColor() {
        return false;
    }

    protected boolean applyDataViewBinding() {
        return false;
    }

    /**
     * 返回需要设置的StatusBar的Color值
     */
    protected int getStatusBarColor() {
        return 0;
    }

    protected int getBackgroundDrawableResource() {
        return 0;
    }

    protected boolean isBlackStatusBarFontColor() {
        return true;
    }

    private View mStatusBarView;

    public void setStatusBarColor(int color) {
        if (mStatusBarView != null) {
            mStatusBarView.setBackgroundColor(color);
        }
    }

    protected View fitsStatusBar(View contentView) {
        mStatusBarView = null;
        int backgroundResource = getBackgroundDrawableResource();
        if (backgroundResource != 0) {
            getWindow().setBackgroundDrawableResource(backgroundResource);
        }

        if (isFullScreen()) {
            return contentView;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        ScreenUtils.setStatusBarFontColor(this, isBlackStatusBarFontColor());

        if (needSetStatusBarColor()) {
            mStatusBarView = new View(this);
            mStatusBarView.setBackgroundColor(getStatusBarColor());

            FrameLayout frameLayout = new FrameLayout(this);
            frameLayout.addView(
                    contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            frameLayout.addView(mStatusBarView,
                    ViewGroup.LayoutParams.MATCH_PARENT, ScreenUtils.getStatusBarHeight(this));
            return frameLayout;
        }
        return contentView;
    }


    public boolean needShare() {
        return false;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mActivityDestroyed = false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }


    ////////////////////////////loading view 相关///////////////////////////////////////////////////////////////
    private LoadingView mLoadingView;
    private AnimationDrawable mLoadingDrawable;

    private void initLoadingView(View view) {
        mLoadingView = new LoadingView(view, v -> refreshDataWithCheckNetWork());
        mLoadingView.setLoadingAnimation(this);
        View v = view.findViewById(R.id.loading_img);
        if (v != null) {
            Drawable drawable = v.getBackground();
            if (drawable instanceof AnimationDrawable) {
                mLoadingDrawable = (AnimationDrawable) drawable;
            }
        }
        showNormal();
    }

    @Override
    public void startLoading() {
        if (mLoadingDrawable != null) {
            if (!mLoadingDrawable.isRunning()) {
                mLoadingDrawable.start();
            }
        }
    }

    @Override
    public void stopLoading() {
        if (mLoadingDrawable != null) {
            mLoadingDrawable.stop();
        }
    }

    protected void initNoDataView(String noDataStr, boolean clickable) {
        if (clickable) {
            mLoadingView.setNoDataTitle(noDataStr, v -> refreshDataWithCheckNetWork());
        } else {
            mLoadingView.setNoDataTitle(noDataStr, null);
        }
    }

    /**
     * 显示原有视图
     */
    public void showNormal() {
        if (isAlive()) {
            mLoadingView.showLoading(0);
        }
    }

    /**
     * 显示加载中
     */
    public void showLoading() {
        if (isAlive()) {
            mLoadingView.showLoading(1);
        }
    }

    /**
     * 显示加载失败
     */
    public void showFailed() {
        if (isAlive()) {
            mLoadingView.showLoading(2);
        }
    }

    /**
     * 显示无内容
     */
    public void showNoData() {
        if (isAlive()) {
            mLoadingView.showLoading(3);
        }
    }

    public boolean isShowingNormal() {
        return mLoadingView.isShowingNormal();
    }

    public boolean isShowingLoading() {
        return mLoadingView.isShowingLoading();
    }

    public boolean isShowingFailed() {
        return mLoadingView.isShowingFailed();
    }

    public boolean isShowingNoData() {
        return mLoadingView.isShowingNoData();
    }

    ////////////////////////////Handler 相关///////////////////////////////////////////////////////////////

    /**
     * 获取handler
     */
    public Handler getHandler() {
        return mActivityHandler;
    }

    protected void handleMessage(Message msg) {
    }

    protected static class ActivityHandler extends Handler {

        private WeakReference<BaseActivity> mActivityWeakReference;

        ActivityHandler(BaseActivity activity) {
            mActivityWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void dispatchMessage(Message msg) {
            BaseActivity activity = mActivityWeakReference.get();
            if (activity != null && activity.isActivityAlive()) {
                super.dispatchMessage(msg);
            }
        }

        @Override
        public void handleMessage(Message msg) {
            BaseActivity activity = mActivityWeakReference.get();
            if (activity != null && activity.isActivityAlive()) {
                activity.handleMessage(msg);
            }
        }
    }
}
